#include "csem_api.h"
/*
需复用v4的某些函数
因此编译csem需携带v4.c
 */
#include "common.h"
#include "csem_impl.h"
#include "formula.h"
#include <stdlib.h>

static uint64_t _cmp_hr_ts(const void *v) {
  smp_hr_t *smp = (smp_hr_t *)v;
  return smp->ts;
}

NEW_CMP(_cmp_smp, uint64_t, _cmp_hr_ts)

static uint64_t _cmp_csem_ts(const void *v) {
  csem_sleep_t *s = (csem_sleep_t *)v;
  return s->ts;
}

NEW_CMP(_cmp_csem, uint64_t, _cmp_csem_ts)

void csem_calc(csem_sleep_t *csem_slps, size_t slp_len, smp_hr_t *hr_list,
               size_t hr_len, sleep_root **root) {
  if (!csem_slps || !slp_len)
    return;
  if (!hr_list || !hr_len)
    return;

  qsort(hr_list, hr_len, sizeof(smp_hr_t), _cmp_smp);
  qsort(csem_slps, slp_len, sizeof(csem_sleep_t), _cmp_csem);

  if (hr_len < 5) {
    if (root)
      *root = NULL;
    return;
  }

  csem_impl(csem_slps, slp_len, hr_list, hr_len, root);
}